/**   
 * @Title: RegistActivity.java 
 * @Package com.fone.player.activity.personal
 * Copyright: Copyright (c) 2014
 * Company: 100TV
 * @Description: 注册界面 
 * @author JasonZue  jczhu@100tv.com   
 * @date 2014-4-28
 * @version V1.0   
 */

package com.fone.player.activity.personal;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.bean.RegistData;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.LoginspaceRst;
import com.fone.player.client.Request;
import com.fone.player.constant.FoneConstant;
import com.fone.player.sns.UserInfoManager;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.LoginUtil;
import com.fone.player.view.LegalNoticeDialog;

/**
 * 注册模块
 * 
 * @author JasonZue
 * @since 2014-4-28
 */
public class RegistActivity extends BaseActivity implements OnClickListener {
	
	private static String TAG = "RegistActivity";
	
	private TextView mTitleTv,registServiceInfoTv;
	private Button mLeftBt, mRightBt;
	private Button mRegistBt;
	private LinearLayout mWaitting;
	@SuppressWarnings("unused")
	private RadioButton mMaleRb,mFemaleRb,mSecret;
	private EditText usernameEt,pswEt,nicknameEt;
	private RadioGroup genderRg;
	public CheckBox registerCheckBox;
	
	private RegistCallBack mRegistCallBack;

	private Handler mHandler;
	private static final int LOGIN_SUCCESS = 1;
	
	private String comefrom,payfrom,clid;//
	private int mFeeType = -1;//
//	private int mFromPage = -1;//
	
	private String tempName = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personal_regist_view);
		initView();
		iniData();
		iniHandler();
	}

	/**
	 * 初始化视图
	 * 
	 * @return void
	 * @throws
	 */
	private void initView() {
		mLeftBt = (Button) findViewById(R.id.common_title_left_bt);
		mRightBt = (Button) findViewById(R.id.common_title_right_bt);
		mRegistBt = (Button) findViewById(R.id.regist_bt);
		mTitleTv = (TextView) findViewById(R.id.common_title_text_tv);
		registServiceInfoTv = (TextView) findViewById(R.id.regist_service_info_tv);
		mMaleRb = (RadioButton) findViewById(R.id.regist_male_rb);
		mFemaleRb = (RadioButton) findViewById(R.id.regist_female_rb);
		mSecret = (RadioButton) findViewById(R.id.regist_secret_rb);
		
		usernameEt = (EditText) findViewById(R.id.regist_username_et);
		pswEt = (EditText) findViewById(R.id.regist_user_pwd_et);
		nicknameEt = (EditText) findViewById(R.id.regist_user_nickname_et);
		genderRg = (RadioGroup) findViewById(R.id.regist_gender_rg);

		registerCheckBox = (CheckBox) findViewById(R.id.regist_service_info_cb);
//		join_vip_ll = (LinearLayout)findViewById(R.id.join_vip_ll);
//		mJoinVipBt = (Button) findViewById(R.id.regist_join_vip_bt);

		mLeftBt.setText("注册");
		mRightBt.setVisibility(View.GONE);
		mTitleTv.setVisibility(View.GONE);
		mMaleRb.setChecked(true);

		mWaitting = (LinearLayout) findViewById(R.id.regist_waitting_ll);

		registServiceInfoTv.setOnClickListener(this);
		mRegistBt.setOnClickListener(this);
//		mJoinVipBt.setOnClickListener(this);
		mLeftBt.setOnClickListener(this);
		mWaitting.setOnClickListener(this);

	}
	
	private void iniData() {
		Intent intent = getIntent();
		comefrom = intent.getStringExtra("loginfrom");
		payfrom = intent.getStringExtra("payfrom");
		clid = intent.getStringExtra("clid");
		mFeeType = intent.getIntExtra("type", -1);
//		comefrom = intent.getStringExtra("from");
//		if (mFeeType == FoneConstants.DO_VIP_ACTION
//				&& join_vip_ll.getVisibility() == View.VISIBLE) {
//			join_vip_ll.setVisibility(View.INVISIBLE);
//		} else {
//			join_vip_ll.setVisibility(View.VISIBLE);
//		}
//		mFeeType = -1;
		mRegistCallBack = new RegistCallBack();
	}
	
	@SuppressLint("HandlerLeak")
	private void iniHandler(){
		mHandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case LOGIN_SUCCESS:
					finish();
					FoneUtil.sendLoginSuccess(mContext,payfrom,mFeeType,false,clid);
					mWaitting.setVisibility(View.GONE);
					FoneUtil.showToast(mContext, "注册成功");
					break;
				default:
					break;
				}
			}
		};
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.common_title_left_bt:
			finish();
			break;
//		case R.id.regist_join_vip_bt:
//			mFonePayManger = FonePayManager.getInstance();
//			mFonePayManger.startPay(FoneConstants.DO_VIP_ACTION, FoneConstants.FROM_REGIST_VIP);
//			break;
		case R.id.regist_service_info_tv:
			LegalNoticeDialog lnDialog = new LegalNoticeDialog(this, FoneUtil.getDeclaration(mContext, FoneConstant.REGISTER_LEGAL_NOTICE));
			lnDialog.setListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					registerCheckBox.setChecked(true);
				}
			});
			break;
		case R.id.regist_bt:
			// 隐藏输入法
			InputMethodManager imm = (InputMethodManager) mContext
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			if (imm != null) {
				imm.hideSoftInputFromWindow(mRegistBt.getWindowToken(), 0);
			}
			
			String username = usernameEt.getText().toString();
			String pwdUser = pswEt.getText().toString();
			String nickName = nicknameEt.getText().toString().trim();
			String gender = "2"; //默认保密
			switch (genderRg.getCheckedRadioButtonId()) {
			case R.id.regist_male_rb:
				gender = "0";//男
				break;
			case R.id.regist_female_rb:
				gender = "1";//女
				break;
			}
			if(FoneUtil.isNetOkWithToast(mContext)){
				if (verifyRegister(username, pwdUser, nickName)) {
					if (registerCheckBox != null && registerCheckBox.isChecked()) {
						tempName = username;
						Object data = getData(username, pwdUser, nickName, gender);
						L.v(TAG, "data" + data.toString());
						if(TextUtils.isEmpty(comefrom)){
							comefrom="5";
						}
						mWaitting.setVisibility(View.VISIBLE);
						Request.getInstance().regspace(1,comefrom, data, mRegistCallBack);
					} else {
						Toast.makeText(mContext, "请认真阅读服务条款", Toast.LENGTH_SHORT)
						.show();
					}
				}
			}
			
			break;
		default:
			break;
		}
	}

	
	/**
	 * 注册信息校验
	 * 
	 * @param userName
	 * @param password
	 * @param nickName
	 * @return
	 */
	public boolean verifyRegister(String userName, String password,
			String nickName) {
		L.v(TAG, "verifyRegister", "userName : " + userName + " password : "
				+ password + " nickName : " + nickName);
		boolean verifyRes = true;
		if (userName == null || userName.trim().equals("")) {
			Toast.makeText(mContext, "请输入用户名", Toast.LENGTH_SHORT).show();
			verifyRes = false;
		} else if (password == null || password.equals("")) {
			Toast.makeText(mContext, "请输入密码", Toast.LENGTH_SHORT).show();
			verifyRes = false;
		} else if (nickName == null || nickName.trim().equals("")) {
			Toast.makeText(mContext, "请输入昵称", Toast.LENGTH_SHORT).show();
			verifyRes = false;
		}

		if (verifyRes) {
			if (!LoginUtil.checkEmailAndMobile(userName)) {
				Toast.makeText(mContext, "请输入正确邮箱或手机号", Toast.LENGTH_SHORT)
						.show();
				verifyRes = false;
			} else if (!LoginUtil.checkPassword(password)) {
				Toast.makeText(mContext, "密码由6-24位英文数字组成", Toast.LENGTH_SHORT)
						.show();
				verifyRes = false;
			} else if (!LoginUtil.checkNickName(nickName)) {
				Toast.makeText(mContext, "昵称太短或太长", Toast.LENGTH_SHORT).show();
				verifyRes = false;
			}
		}

		return verifyRes;
	}
	
	
	/**
	 * 封装请求数据
	 * @param username
	 * @param pwdUser
	 * @param nickName
	 * @return
	 */
	public Object getData(String username,String pwdUser,String nickName,String gender){
		RegistData data = new RegistData();
			data.userid = username;
			data.pwd = pwdUser;
			data.nickname = FoneUtil.Base64Encode(nickName);
			data.gender = gender;
		return data;
	}
	
	/**
	 * 注册完毕后回调
	 * @author user
	 *
	 */
	private class RegistCallBack implements Callback<LoginspaceRst>{

		@Override
		public void onSuccess(final LoginspaceRst t) {
			L.v(TAG, "RegistCallBack onSuccess", t.toString());
			if(t.result!=0){
				tempName = null;
				if(t.error!=null){
					try{
						switch (Integer.valueOf(t.error.errorcode)) {
						case 112:
							FoneUtil.showToast(mContext, "昵称不符合要求，请更换");
							break;
						case 114:
							FoneUtil.showToast(mContext, "该帐号已注册");
							break;
						case 707:
							FoneUtil.showToast(mContext, "抱歉，昵称已存在，请重新填写");
							break;
						default:
							FoneUtil.showToast(mContext, "注册失败，请稍后重试");
							break;
						}
					}catch(Exception e){
						FoneUtil.showToast(mContext, "注册失败，请稍后重试");
					}
					mWaitting.setVisibility(View.GONE);
					return ;
				}
			}
			//本地信息保存
			new Thread(){
				public void run() {
					UserInfoManager.saveLoginUserInfo(t, UserInfoManager.NEW_USER);
					UserInfoManager.saveHistoricalUserList(tempName);
					tempName = null;
					mHandler.sendEmptyMessage(LOGIN_SUCCESS);
				};
			}.start();
		}

		@Override
		public void onFailure(Error error) {
			mWaitting.setVisibility(View.GONE);
			tempName = null;
			L.v(TAG,
					"LoginCallBack onFailure",
					"isNetworkError : " + error.isNetworkError() + " status : "
							+ error.getStatus() + " reason : "
							+ error.getReason());
			
			if(error.isNetworkError()){
				FoneUtil.showToast(mContext, "网络超时,请稍后重试");
				return ;
			}
			FoneUtil.showToast(mContext, "注册失败，请稍后重试");
		}
		
	}
	
}
